package com.huike.common.utils;

import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;
import io.minio.messages.Bucket;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;

@Component
public class MinioUtils {
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.port}")
    private Integer port;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.configDir}")
    private String configDir;

    private static MinioClient minioClient;

    public MinioClient getInstance(){
        if (minioClient == null){
            minioClient = MinioClient.builder().endpoint(endpoint,port,false).credentials(accessKey,secretKey).build();
        }
        return minioClient;
    }

    public List<Bucket> getAllBucket() throws Exception {
        // 获取minio中所以的bucket
        List<Bucket> buckets = getInstance().listBuckets();
        return buckets;
    }

    public void uploadToMinio(MultipartFile file,String fileName){
        try{
            getInstance().putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .contentType(file.getContentType())
                            .stream(file.getInputStream(),file.getInputStream().available(),-1)
                            .build());
        } catch (Exception e){
            e.printStackTrace();
        }
    }

//    public String getUrlByObjectName(String objectName){
//        String objectUrl = null;
//        try{
//            objectUrl = getInstance().getPresignedObjectUrl();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }
}
